package com.imy.luascript.viewmodel;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.imy.luascript.app.data.BaseResponse;
import com.imy.luascript.retrofit.ApiException;
import com.imy.luascript.retrofit.HttpResultSubscriber;
import com.imy.luascript.retrofit.OnRequestCallBackListener;
import com.imy.luascript.retrofit.TransformUtils;

import rx.Observable;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * @ProjectName: frame
 * @Package: com.imy.frame.model
 * @ClassName: BasePresenter
 * @Description: 描述
 * @Author: Imy
 * @CreateDate: 2020/10/26 15:54
 */
public abstract class BaseViewModel extends ViewModel {
    private static final String TAG = "BaseViewModel";
    public CompositeSubscription mCompositeSubscription;
    protected MutableLiveData<String> mExceptionMsg;
    public static final String ON_LOAD_NETWORK_ERROR = "ON_LOAD_NETWORK_ERROR";
    protected BaseImplView implView;

    public BaseViewModel(BaseImplView implView) {
        this.implView = implView;
    }

    //添加一个Subscription
    public void addSubscription(Subscription s) {
        if (this.mCompositeSubscription == null) {
            this.mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(s);
    }

    public MutableLiveData<String> getExceptionMsg() {
        if (mExceptionMsg == null) {
            mExceptionMsg = new MutableLiveData<>();
        }
        return mExceptionMsg;
    }

    public void clearSubscription() {
        if (this.mCompositeSubscription != null) {
            this.mCompositeSubscription.clear();
        }
    }

    protected void unSubscribe() {
        if (this.mCompositeSubscription != null) {
            this.mCompositeSubscription.unsubscribe();
            mCompositeSubscription = null;
        }
    }


    @Override
    public void onCleared() {
        super.onCleared();
        unSubscribe();
        Log.d(TAG, "onCleared: 内容清除中。。。");
    }

    public <T> void startRequest(Observable<BaseResponse<T>> request, OnRequestCallBackListener<T> listener) {
        addSubscription(request.compose(TransformUtils.defaultSchedulers())
                .subscribe(new HttpResultSubscriber<T>() {

                    @Override
                    public void onSuccess(T t) {
                        if (listener != null && t != null) {
                            listener.onSuccess(t);
                        }
                    }

                    @Override
                    public void onError(ApiException e) {
                        if (listener != null) {
                            listener.onError(e);
                        }
                        //针对不同情况进行处理

                    }
                }));
    }

}